﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using net8.Helper;
using System.Text.Json.Serialization;

namespace net8.Controllers
{
    [ApiExplorerSettings(IgnoreApi = true)]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [AllowAnonymous]
    public class FilmController : ControllerBase
    {
        private readonly BiYingNiaoConfig Config = AppConfig.Configuration.GetSection("BiYingNiaoConfig").Get<BiYingNiaoConfig>();

        ///// <summary>
        ///// 获取城市列表
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet]
        //public async Task<List<BiYingNiaoCityList>> GetCityList(int canel)
        //{
        //    Config.Canal = canel;
        //    Dictionary<string, string> headers = GetParam();
        //    string url = Config.Url + "/api/v3/movie/citiers?page=1&page_size=1000&canal=" + Config.Canal;
        //    var res = await HttpHelper.GetJsonAsync1<BynResult<BiYingNiaoCityData>>(url, headers);
        //    return res.data.data;
        //}

        /// <summary>
        /// 影院列表
        /// </summary>
        /// <param name="cityCode"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<LanPage> GetCinemasList([FromQuery] FilmPage model)
        {
            Config.Canal = model.Canel;
            Dictionary<string, string> headers = GetParam();
            var res = await HttpHelper.GetAsync<FilmResult<List<BiYingNiaoCinemaList>>>(Config.Url + "/api/v3/movie/cinemas?city_id=" + model.CityCode + "&canal=" + Config.Canal, headers);

            int total = 0;
            List<BiYingNiaoCinemaList> list = new List<BiYingNiaoCinemaList>();
            if (res.code == 0)
            {
                list = res.data;
                total = res.data.Count;
                if (!string.IsNullOrEmpty(model.Keyword))
                {
                    list = list.Where(c => c.cinema_name.Contains(model.Keyword)).ToList();
                    total = list.Count;
                }

                list = list.Skip((model.PageIndex - 1) * model.PageSize).Take(model.PageSize).ToList();
            }

            LanPage result = new LanPage()
            {
                Total = total,
                Data = list,
            };
            return result;
        }

        [HttpGet]
        public async Task<FilmResult> GetFilmList([FromQuery] FilmParam model)
        {
            Dictionary<string, string> headers = GetParam();
            string url = Config.Url + "/api/v3/movie/hot?city_id=" + model.cityCode + "&canal=" + Config.Canal;
            FilmResult<List<HotList>> filmResult = await HttpHelper.GetAsync<FilmResult<List<HotList>>>(url, headers);

            if (filmResult.code != 0)
            {
                return new FilmResult()
                {
                    code = filmResult.code,
                    message = filmResult.message
                };
            }

            headers = GetParam();
            url = Config.Url + "/api/v3/movie/schedule?cinema_id=" + model.cinemaId + "&canal=" + Config.Canal;
            FilmResult<List<ScheduleList>> scheduleResult = await HttpHelper.GetAsync<FilmResult<List<ScheduleList>>>(url, headers);
            if (scheduleResult.code != 0)
            {
                return new FilmResult()
                {
                    code = filmResult.code,
                    message = filmResult.message
                };
            }

            if (scheduleResult.data == null)
            {
                return new FilmResult()
                {
                    code = 1,
                    message = "暂无排期"
                };
            }

            List<FilmList> filmList = new List<FilmList>();
            List<FilmSchedule> scheduleList = new List<FilmSchedule>();
            foreach (var item in filmResult.data ?? new List<HotList>())
            {

                var dayList = scheduleResult.data.Where(s => s.film_id == item.film_id).ToList();

                double lowPrice = 0;
                if (dayList.Count > 0)
                {
                    lowPrice = dayList.OrderBy(s => s.sale_price).FirstOrDefault()?.sale_price ?? 0;
                }
                else
                {
                    continue;
                }

                FilmList entity = new FilmList()
                {
                    id = item.film_id,
                    description = item.intro,
                    director = item.director,
                    duration = item.duration,
                    openTime = item.publish_date.Substring(0, 10),
                    leadingRole = item.cast,
                    type = item.film_types,
                    openDay = item.publish_date,
                    poster = item.pic.Replace("300", "800"),
                    language = item.language,
                    remark = Convert.ToDouble(item.grade),
                    showName = item.name,
                    showMark = item.version_types,
                    Price = lowPrice
                };
                filmList.Add(entity);

                foreach (var schedule in dayList)
                {
                    DateTime closeTime = DateTime.Parse(schedule.show_time).AddMinutes(schedule.duration);
                    FilmSchedule entity11 = new FilmSchedule()
                    {
                        id = schedule.show_id,
                        showId = schedule.film_id,
                        showTime = schedule.show_time,
                        showDate = schedule.show_time.Substring(0, 10),
                        cinemaId = schedule.cinema_id,
                        hallName = schedule.hall_name,
                        price = schedule.sale_price,
                        showVersion = schedule.show_version_type,
                        closeTime = closeTime.ToString("yyyy-MM-dd HH:mm:ss")
                    };
                    scheduleList.Add(entity11);
                }
            }

            return new FilmResult()
            {
                code = 0,
                message = "返回成功",
                data = new { filmList, scheduleList }
            };
        }

        private Dictionary<string, string> GetParam()
        {
            string t = CurrentTime();
            string v = Config.V;
            string appSecret = Config.AppSecret;
            string param = Config.V + appSecret + t + appSecret;
            string sign = SecurityHelper.Md5(param);

            Dictionary<string, string> headers = new Dictionary<string, string>
            {
                { "app-key", Config.AppKey },
                { "sign", sign },
                { "t", t },
                { "v", v }
            };
            return headers;
        }

        /// <summary>
        /// 获取当前时间戳
        /// </summary>
        /// <returns></returns>
        private string CurrentTime()
        {
            DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return (DateTime.Now.AddHours(-8) - Jan1st1970).TotalSeconds.ToString();
        }
    }

    /// <summary>
    /// 必应鸟配置
    /// </summary>
    public class BiYingNiaoConfig
    {
        /// <summary>
        /// 请求地址
        /// </summary>
        public string Url { get; set; }

        /// <summary>
        /// 应用标识
        /// </summary>
        public string AppKey { get; set; }

        /// <summary>
        /// 版本
        /// </summary>
        public string V { get; set; }

        /// <summary>
        /// 密钥
        /// </summary>
        public string AppSecret { get; set; }

        /// <summary>
        /// 渠道 2新版
        /// </summary>
        public int Canal { get; set; }
    }

    public class FilmResult<T>
    {
        public int code { get; set; }
        public string message { get; set; }
        public T data { get; set; }
    }

    public class FilmResult
    {
        public int code { get; set; }
        public string message { get; set; }
        public object data { get; set; }
    }

    public class BynResult<T> : IHttpResult
    {
        /// <summary>
        /// 
        /// </summary>
        [JsonPropertyName("code")]
        public string Status { get; set; }

        [JsonPropertyName("message")]
        public string Message { get; set; }

        public T data { get; set; }
    }

    public class BiYingNiaoCityData
    {
        public List<BiYingNiaoCityList> data { get; set; }
    }

    public class BiYingNiaoCityList
    {
        public int city_id { get; set; }
        public string name { get; set; }
        public string sname { get; set; }
    }


    public class BiYingNiaoCinemaList
    {
        public int cinema_id { get; set; }
        public int city_id { get; set; }
        public string cinema_name { get; set; }
        public string address { get; set; }
        public float latitude { get; set; }
        public float longitude { get; set; }
        public string phone { get; set; }
        public string region_name { get; set; }
        public string distance { get; set; }
        public string show_id { get; set; }
        public string show_time { get; set; }
        public string hall_name { get; set; }
    }

    public class FilmParam
    {
        public string cityCode { get; set; }
        public string cinemaId { get; set; }
    }

    public class HotList
    {
        public int film_id { get; set; }
        public string grade { get; set; }
        public string name { get; set; }
        public int duration { get; set; }
        public string publish_date { get; set; }
        public string director { get; set; }
        public string cast { get; set; }
        public string intro { get; set; }
        public string version_types { get; set; }
        public string language { get; set; }
        public string film_types { get; set; }
        public string pic { get; set; }
        public int like_num { get; set; }
        public int show_status { get; set; }
    }

    public class ScheduleList
    {
        public int sale_price { get; set; }
        public int cinema_id { get; set; }
        public string hall_name { get; set; }
        public int film_id { get; set; }
        public string film_name { get; set; }
        public string show_id { get; set; }
        public int duration { get; set; }
        public string show_time { get; set; }
        public string stop_sell_time { get; set; }
        public string show_version_type { get; set; }
        public int net_price { get; set; }
        public string language { get; set; }
        public string plan_type { get; set; }
        public List<Schedule_Area> schedule_area { get; set; }
    }

    public class Schedule_Area
    {
        public int net_price { get; set; }
        public int sale_price { get; set; }
        public string area { get; set; }
        public int service_fee { get; set; }
    }

    public class FilmList
    {
        /// <summary>
        /// 影片背景图
        /// </summary>
        public string backgroundPicture { get; set; }

        /// <summary>
        /// 精彩点评
        /// </summary>
        public string highlight { get; set; }

        /// <summary>
        /// 首映日期格式：YYYY-MM-DD,YYYY-MM，已废弃
        /// </summary>
        public string openTime { get; set; }

        /// <summary>
        /// 影片类型，内容如：2D、IMAX3D、3D、IMAX、剧情、其他等
        /// </summary>
        public List<string> showVersionList { get; set; }

        /// <summary>
        /// 影片版本
        /// </summary>
        public string showMark { get; set; }

        /// <summary>
        /// 影片简介
        /// </summary>
        public string description { get; set; }

        /// <summary>
        /// 海报
        /// </summary>
        public string poster { get; set; }

        /// <summary>
        /// 海报地址
        /// </summary>
        public string posterPath { get; set; }

        /// <summary>
        /// 剧照
        /// </summary>
        public List<string> trailerList { get; set; }

        /// <summary>
        /// 首映日
        /// </summary>
        public string openDay { get; set; }

        /// <summary>
        /// 影片播放时长
        /// </summary>
        public int duration { get; set; }

        /// <summary>
        /// 对白语言
        /// </summary>
        public string language { get; set; }

        /// <summary>
        /// 国家
        /// </summary>
        public string country { get; set; }

        /// <summary>
        /// 影片类型
        /// </summary>
        public string type { get; set; }

        /// <summary>
        /// 主演
        /// </summary>
        public string leadingRole { get; set; }

        /// <summary>
        /// 导演
        /// </summary>
        public string director { get; set; }

        /// <summary>
        /// 影片名称
        /// </summary>
        public string showName { get; set; }

        /// <summary>
        /// 影片名称(英文)
        /// </summary>
        public string showNameEn { get; set; }

        /// <summary>
        /// 影片
        /// </summary>
        public long id { get; set; }

        /// <summary>
        /// 评分
        /// </summary>
        public double remark { get; set; }

        public double Price { get; set; }
    }

    public class FilmSchedule
    {
        /// <summary>
        /// 影片上映日期，格式 YYYY-MM-DD
        /// </summary>
        public string showDate { get; set; }

        /// <summary>
        /// 服务费，单位分
        /// </summary>
        public double serviceFee { get; set; }

        /// <summary>
        /// 价格，包含服务费，单位分
        /// </summary>
        public double price { get; set; }

        /// <summary>
        /// 影厅名称
        /// </summary>
        public string hallName { get; set; }

        /// <summary>
        /// 影片 id
        /// </summary>
        public long showId { get; set; }

        /// <summary>
        /// 是否已过期
        /// </summary>
        public bool isExpired { get; set; }

        /// <summary>
        /// 影片版本
        /// </summary>
        public string showVersion { get; set; }

        /// <summary>
        /// 影院 id
        /// </summary>
        public int cinemaId { get; set; }

        /// <summary>
        /// 场次开始时间，即影片开始播放的时间
        /// </summary>
        public string showTime { get; set; }

        /// <summary>
        /// 场次 id
        /// </summary>
        public string id { get; set; }

        /// <summary>
        /// 场次结束时间，场次开始时间加上影片放映时长即场次结束时间
        /// </summary>
        public string closeTime { get; set; }

        /// <summary>
        /// 同一个场次最多可购买的座位数，不同系统商，值可能不同
        /// </summary>
        public int maxCanBuy { get; set; }

        /// <summary>
        /// 影厅 id
        /// </summary>
        public string hallId { get; set; }

        /// <summary>
        /// 分区价格
        /// </summary>
        public string scheduleArea { get; set; }
    }

    public class FilmPage : BasePage
    {
        public string CityCode { get; set; }
        public string Keyword { get; set; }
        public int Canel { get; set; }
    }

    public class BasePage
    {
        public int PageIndex { get; set; }
        public int PageSize { get; set; }
    }

    public class LanPage
    {
        public int Total { get; set; }
        public object Data { get; set; }
    }
}
